import { _decorator, Component, instantiate, Node, NodePool, Prefab } from 'cc';
const { ccclass, property } = _decorator;

interface IDict {
    [name: string]: NodePool;
}

@ccclass('PoolManager')
export class PoolManager {

    public static instance() {
        if (!this._instance) {
            this._instance = new PoolManager();

        }
        return this._instance;
    }

    private static _instance: PoolManager = null;

    private dict: IDict = {}

    public get(prefab: Prefab, parent: Node) {
        let name = prefab.data.name;
        let node: Node = null;
        const nodePool = this.dict[name];

        if (nodePool) {
            if (nodePool.size() > 0) {
                node = nodePool.get();
                node = instantiate(prefab);
                console.info(name+" size ="+nodePool.size())
            } else {

                node = instantiate(prefab);
            }
        } else {
            this.dict[name] = new NodePool();

            node = instantiate(prefab);
        }

        node.parent = parent;
        node.active = true;
        return node;
    }

    public put(node: Node) {

        if (!this.dict[node.name]) {
            this.dict[node.name] = new NodePool();
        }

        this.dict[node.name].put(node);

        node.parent = null;
    }
}

